#-*- coding: utf-8 -*-
#! /usr/bin/python

#######################################################################################
#                                                                                     #
#    File: online_keeper.py                                                           #
#    Part of 51cto_cheater                                                         #
#    Home: http://51cto-cheater.googlecode.com                                     #
#                                                                                     #
#    The MIT License                                                                  #
#                                                                                     #
#    Copyright (c) 2010-2011 <araya.akashic@gmail.com>                                #
#                                                                                     #
#    Permission is hereby granted, free of charge, to any person obtaining a copy     #
#    of this software and associated documentation files (the "Software"), to deal    #
#    in the Software without restriction, including without limitation the rights     #
#    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell        #
#    copies of the Software, and to permit persons to whom the Software is            #
#    furnished to do so, subject to the following conditions:                         #
#                                                                                     #
#    The above copyright notice and this permission notice shall be included in       #
#    all copies or substantial portions of the Software.                              #
#                                                                                     #
#    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR       #
#    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,         #
#    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE      #
#    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER           #
#    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,    #
#    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN        #
#    THE SOFTWARE.                                                                    #
#                                                                                     #
#######################################################################################
# This code is to automatically do daily task for 51cto bbs

# Author: Araya
# Modified: elsesky

import time
import socket
import urllib,urllib2,cookielib,re,random
import base64

defaulttimeout = 3
socket.setdefaulttimeout(defaulttimeout)

class Login:
    _login_url = 'http://home.51cto.com/index.php?s=/Index/doLogin'
    _method = 'post'
    # email 填写 51cto 登录用户名或邮箱
    # passwd 填写 51cto 登录密码
    _login_data = {
                   'email':'',\
                   'passwd':'',\
            }
    _headers = [
                ('host','home.51cto.com'),\
                ('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2'),\
                ('Referer','http://home.51cto.com/index.php?s=/Index/index/reback/http%253A%252F%252Fwww.51cto.com%252F/')\
        ]
    _data = {
             'cookie_file_path':"51cto_cookies.dat"
        }
    _re = r'src="(.+?)"'
    _version = '0.1'
    _connect_info = {}
    def __init__(self,user,passwd):
        #         注意,先初始化,然后再封装
        self._login_data = {
                   'email':user,\
                   'passwd':passwd,\
            } 
        self._data= {
             'cookie_file_path':str(user).decode('utf8').encode('GBK')+"_51cto_cookies.dat"
        }
        
        self._connect_info['cookie'] = cookielib.LWPCookieJar()
        try:
            self._connect_info['cookie'].revert(self._data['cookie_file_path'])
        except Exception,e:
            print e
        self._connect_info['cookie_processor'] = urllib2.HTTPCookieProcessor(self._connect_info['cookie'])

        self._connect_info['post_data'] = urllib.urlencode(self._login_data)
        
        
    def open(self):
        opener = urllib2.build_opener(self._connect_info['cookie_processor'])
        opener.addheaders = self._headers
        urllib2.install_opener(opener)
        # opener.open(request)
        request = urllib2.Request(self._login_url,self._connect_info['post_data'])
        conn = opener.open(request)
        if(conn.geturl() == self._login_url):
            self._connect_info['cookie'].save(self._data['cookie_file_path'])
        else:
            pass
        # 根据 js 中的链接连接登录
        partner = re.compile(self._re)
        match = partner.findall(conn.read())
        for item in match:
#             print item
            try:
                opener.open(item)
            except  urllib2.HTTPError,e:
                print e
                continue
        # 登录成功开始领豆
        url = 'http://down.51cto.com/download.php'
        data = {'do':'getfreecredits','t':random.random()}
        opener.open(url, urllib.urlencode(data))
        # html = opener.open('http://down.51cto.com/')
        # 领下载豆
        url = 'http://home.51cto.com/index.php?s=/Home/toSign'
        data = {'s':''}
        result = opener.open(url, urllib.urlencode(data))
        fp = open('log.log',"a")
        fp.write("完成时间:".decode('utf8').encode('GBK') + time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) + " 返回内容:".decode('utf8').encode('GBK') + result.read() + "\n")
        fp.close()
    

if __name__ == "__main__":
    print "end"